package logic

import (
	"context"
	"errors"
	"hema-fresh/model/mysql"

	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加方法
func (l *ShopAddLogic) ShopAdd(in *hemarpc.ShopAddRequest) (*hemarpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Begin()

	var shops mysql.Shop

	if err := shops.FindShopByTitle(mysql.DB, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("当前商品已存在")
	}

	var class mysql.Class

	if err := class.FindClassByName(begin, in.ClassName); err != nil {
		class = mysql.Class{
			Name: in.ClassName,
		}

		if err := class.CLassAdd(begin); err != nil {
			begin.Rollback()
			return nil, errors.New("分类添加失败")
		}
	}

	shop := &mysql.Shop{
		Title:   in.Title,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		ClassId: int64(class.ID),
	}

	err := shop.ShopAdd(begin)
	if err != nil {
		return nil, err
	}

	return &hemarpc.ShopAddResponse{
		ShopsId: int64(shop.ID),
	}, nil
}
